<template>
  <div class="employee-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>员工管理</span>
          <el-button type="primary" @click="handleAdd">新增员工</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :model="searchForm" inline>
          <el-form-item label="员工ID">
            <el-input v-model="searchForm.id" placeholder="请输入员工ID" clearable/>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable/>
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable/>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
                v-model="searchForm.status"
                placeholder="请选择状态"
                clearable
                style="width: 120px"
            >
              <el-option label="启用" :value="1"/>
              <el-option label="禁用" :value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 员工列表 -->
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column prop="username" label="用户名"/>
        <el-table-column prop="name" label="姓名"/>
        <el-table-column prop="phone" label="手机号"/>
        <el-table-column prop="sex" label="性别" width="80"/>
        <el-table-column prop="idNumber" label="身份证号"/>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
                size="small"
                :type="row.status === 1 ? 'danger' : 'success'"
                @click="handleStatusChange(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pageParams.page"
            v-model:page-size="pageParams.pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 员工编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
        @close="handleDialogClose"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              show-password
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input v-model="form.idNumber" placeholder="请输入身份证号"/>
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="isEdit">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted, watch} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {employeeApi} from '@/api/admin'

const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const formRef = ref()
const tableData = ref([])
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  id: '',
  name: '',
  username: '',
  status: ''
})

// 分页参数
const pageParams = reactive({
  page: 1,
  pageSize: 10
})

// 表单数据
const form = reactive({
  id: null,
  username: '',
  name: '',
  password: '',
  phone: '',
  sex: '男',
  idNumber: '',
  status: 1
})

// 表单验证规则
const rules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur'}
  ],
  name: [
    {required: true, message: '请输入姓名', trigger: 'blur'},
    {min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur'}
  ],
  sex: [
    {required: true, message: '请选择性别', trigger: 'change'}
  ],
  idNumber: [
    {required: true, message: '请输入身份证号', trigger: 'blur'},
    {pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号格式', trigger: 'blur'}
  ]
}

const isEdit = computed(() => !!form.id)
const dialogTitle = computed(() => isEdit.value ? '编辑员工' : '新增员工')

// 保存查询条件到本地存储
const saveSearchConditions = () => {
  const conditions = {
    searchForm: {...searchForm},
    pageParams: {...pageParams}
  }
  localStorage.setItem('employeeSearchConditions', JSON.stringify(conditions))
}

// 从本地存储恢复查询条件
const restoreSearchConditions = () => {
  const saved = localStorage.getItem('employeeSearchConditions')
  if (saved) {
    try {
      const conditions = JSON.parse(saved)
      Object.assign(searchForm, conditions.searchForm)
      Object.assign(pageParams, conditions.pageParams)
      return true
    } catch (error) {
      console.error('恢复查询条件失败:', error)
      return false
    }
  }
  return false
}

// 清除保存的查询条件
const clearSearchConditions = () => {
  localStorage.removeItem('employeeSearchConditions')
}

// 加载员工数据
const loadEmployeeData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      ...pageParams
    }

    // 添加搜索条件
    if (searchForm.id) {
      params.id = searchForm.id
    }
    if (searchForm.name) {
      params.name = searchForm.name
    }
    if (searchForm.username) {
      params.username = searchForm.username
    }
    if (searchForm.status !== '') {
      params.status = searchForm.status
    }

    // 调用分页查询接口
    const res = await employeeApi.page(params)
    tableData.value = res.data.records || []
    total.value = res.data.total || 0

    // 保存查询条件
    saveSearchConditions()
  } catch (error) {
    ElMessage.error('加载员工数据失败')
    console.error('加载员工数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pageParams.page = 1 // 重置到第一页
  loadEmployeeData()
}

// 重置搜索条件
const handleReset = () => {
  Object.assign(searchForm, {
    id: '',
    name: '',
    username: '',
    status: ''
  })
  pageParams.page = 1
  loadEmployeeData()
  clearSearchConditions()
}

// 新增员工
const handleAdd = () => {
  Object.assign(form, {
    id: null,
    username: '',
    name: '',
    password: '',
    phone: '',
    sex: '男',
    idNumber: '',
    status: 1
  })
  dialogVisible.value = true
}

// 编辑员工
const handleEdit = (row) => {
  Object.assign(form, {
    ...row,
    // 确保密码字段为空，避免更新时修改密码
    password: ''
  })
  dialogVisible.value = true
}

// 状态变更
const handleStatusChange = async (row) => {
  try {
    const action = row.status === 1 ? '禁用' : '启用'
    await ElMessageBox.confirm(
        `确定要${action}员工 "${row.name}" 吗？`,
        '提示',
        {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }
    )

    const newStatus = row.status === 1 ? 0 : 1
    await employeeApi.updateStatus(newStatus, row.id)
    ElMessage.success(`${action}成功`)

    // 重新加载数据
    loadEmployeeData()
  } catch (error) {
    // 用户取消操作
    console.log('用户取消操作')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate()
  if (!valid) return

  submitLoading.value = true
  try {
    if (isEdit.value) {
      // 编辑员工
      const updateData = {
        id: form.id,
        username: form.username,
        name: form.name,
        phone: form.phone,
        sex: form.sex,
        idNumber: form.idNumber,
        status: form.status
      }
      // 如果有密码且不为空，则更新密码
      if (form.password) {
        updateData.password = form.password
      }

      await employeeApi.update(updateData)
      ElMessage.success('更新成功')
    } else {
      // 新增员工
      await employeeApi.register(form)
      ElMessage.success('创建成功')
    }

    dialogVisible.value = false

    // 重新加载数据
    loadEmployeeData()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
    console.error('操作失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 对话框关闭处理
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 分页大小改变
const handleSizeChange = (newSize) => {
  pageParams.pageSize = newSize
  pageParams.page = 1
  loadEmployeeData()
}

// 页码改变
const handlePageChange = (newPage) => {
  pageParams.page = newPage
  loadEmployeeData()
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 监听搜索条件变化，自动保存
watch([searchForm, pageParams], () => {
  // 防抖处理，避免频繁保存
  clearTimeout(window.saveTimeout)
  window.saveTimeout = setTimeout(() => {
    saveSearchConditions()
  }, 500)
}, {deep: true})

// 页面加载时，如果有缓存的查询条件，可以自动查询
onMounted(() => {
  // 从本地存储恢复查询条件
  const hasRestored = restoreSearchConditions()

  // 如果有恢复的条件，自动查询；否则加载第一页数据
  if (hasRestored) {
    loadEmployeeData()
  } else {
    // 默认加载第一页数据
    loadEmployeeData()
  }
})
</script>

<style scoped>
.employee-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.search-form .el-form-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
